import { getTime } from '@/api/common'

import IBaseObj from '#/index'

/**
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time: any, cFormat = '') {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: IBaseObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

// 获取网络时间，有些电脑会有缓存
export function getNetTime() {
  return new Promise((resolve, reject) => {
    const xhr = XMLHttpRequest
      ? new XMLHttpRequest()
      : new window.ActiveXObject('Microsoft.XMLHTTP')

    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          try {
            const time = xhr.getResponseHeader('Date')
            resolve(new Date(time))
          } catch (e) {
            reject(e)
          }
        } else {
          reject(new Error(xhr.statusText))
        }
      } else {
        return null
      }
    }

    xhr.open('get', '/')
    xhr.send(null)
  })
}

// 获取服务器时间
export function getServerTime() {
  return getTime()
}

// 设置 00:00:00
export function setStartTime(date: Date) {
  date.setHours(0)
  date.setMinutes(0)
  date.setSeconds(0)
}

// 设置23:59:59
export function setEndTime(date: Date) {
  date.setHours(23)
  date.setMinutes(59)
  date.setSeconds(59)
}
